<!-- 孔德嘉 个人信息修改 -->
<template>
  <div>
    <el-col :span="8">
      <el-card shadow="hover" class="left_card">
        <p class="header">个人信息</p>
        <div class="img">
          <div
            class="img_center"
            @mouseenter="handleMouseEnter"
            @mouseleave="handleMouseLeave"
          >
            <img v-if="imageUrl" :src="imageUrl" class="img_avg" />
            <img
              v-else
              class="img_avg"
              :src="$imageUrl  + user.avatarId"
            />
            <!-- 图片上传 -->
            <div class="upload_img" v-show="isShowUpload">
              <el-upload
                class="avatar-uploader"
                action="getImageById?id='+this.avatarId"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>   
          </div>
        </div>
        <ul class="user_info">
          <li>
            <i class="el-icon-user-solid"></i><span class="title">用户名</span
            ><span class="info">{{ user.userName }}</span>
          </li>
          <li>
            <i class="el-icon-user"></i><span class="title">登录名称</span
            ><span class="info">{{ user.loginName }}</span>
          </li>
          <li>
            <i class="el-icon-mobile-phone"></i><span class="title">手机号</span
            ><span class="info">{{ user.phone }}</span>
          </li>
          <li>
            <i class="el-icon-message"></i><span class="title">邮箱</span
            ><span class="info">{{ user.email }}</span>
          </li>
          <li>
            <i class="el-icon-date"></i><span class="title">年龄</span
            ><span class="info">{{ user.age }}</span>
          </li>
          <li>
            <i class="el-icon-location-outline"></i
            ><span class="title">地址</span
            ><span class="info">{{ user.address }}</span>
          </li>
          <li>
            <i class="el-icon-timer"></i><span class="title">最后登录时间</span
            ><span class="info">{{ user.lastLoginTime }}</span>
          </li>
        </ul>
      </el-card>
    </el-col>
    <el-col :span="15" :offset="1">
      <el-card shadow="hover" class="right_card">
        <p class="header">基本资料</p>
        <el-tabs
          style="padding: 20px 20px"
          v-model="rightTags"
          @tab-click="handleClick"
        >
          <el-tab-pane label="基本信息" name="first">
            <el-form
              :model="userInfoForm"
              :rules="userInfoRules"
              ref="userInfoForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item label="用户名" prop="userName">
                <el-input v-model="userInfoForm.userName"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="userInfoForm.phone"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="userInfoForm.email"></el-input>
              </el-form-item>
              <el-form-item label="年龄" prop="age">
                <el-input v-model.number="userInfoForm.age"></el-input>
              </el-form-item>
              <el-form-item label="地址" prop="address">
                <el-input v-model="userInfoForm.address"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="upUserInfo('userInfoForm')"
                  >保存</el-button
                >
                <el-button @click="resetForm('userInfoForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="修改密码" name="second">
            <el-form
              :model="passForm"
              status-icon
              :rules="rules"
              ref="passForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item label="旧密码" prop="password">
                <el-input
                  type="password"
                  v-model="passForm.password"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  type="password"
                  v-model="passForm.newPassword"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="checkPass">
                <el-input
                  type="password"
                  v-model="passForm.checkPass"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="updatePassword('passForm')"
                  >提交</el-button
                >
                <el-button @click="resetForm('passForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col>
  </div>
</template>

<script>
export default {
  name: 'user-info',
  data () {
    const validateOldPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        // 判断是否和旧密码一致
        checkOldPassword(this.id, value).then((res) => {
          if (res.data.flag) {
            callback()
          } else {
            callback(new Error('密码错误'))
          }
        })
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.passForm.checkPass !== '') {
          this.$refs.passForm.validateField('checkPass')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      passForm: {
        password: '',
        newPassword: '',
        checkPass: ''
      },
      rules: {
        password: [{ validator: this.validateOldPass, trigger: 'blur' }],
        newPassword: [{ validator: validatePass, trigger: 'blur' }],
        checkPass: [{ validator: validatePass2, trigger: 'blur' }]
      },
      userInfoForm: {
        // userName:"",
        // phone:"",
        // email:"",
        // age:"4545",
        // address:""
      },
      userInfoRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请填写手机号码', trigger: 'blur' },
          {
            min: 11,
            max: 11,
            message: '手机号码不低于11位数',
            trigger: 'blur'
          },
          {
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确的手机号码格式'
          }
        ],
        email: [
          { required: true, message: '请填写邮箱', trigger: 'blur' },
          {
            pattern:
              /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
            message: '请输入正确的邮箱格式'
          }
        ],
        age: [
          {
            type: 'number',
            message: '请填写数字',
            trigger: 'blur'
          }
        ]
      },
      rightTags: 'first',
      id: window.sessionStorage.getItem('userId'),
      isShowUpload: false, // 上传图片遮盖
      user: [], // 用户信息
      imageUrl: '', // 图片路径
      file: File // 图片文件
    }
  },
  mounted () {
    this.getUserInfo()
  },
  methods: {
    // 判断是否和旧密码一致
    validateOldPass (rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        // 判断是否和旧密码一致
        this.$axios({
          method: 'get',
          url: '/sysUser/checkOldPassword',
          params: { id: this.id, password: value }
        }).then((res) => {
          if (res.data.flag == false) {
            callback(new Error('密码错误'))
          } else {
            callback()
          }
        })
      }
    },
    // 获取用户信息
    getUserInfo () {
      this.$axios({
        method: 'get',
        url: '/sysUser/getSysUserById',
        params: { id: this.id }
      }).then((res) => {
        if (res.data.flag == true) {
          this.user = res.data.data
          this.userInfoForm = res.data.data
       
        } else {
          this.$message.warning('查询失败')
        }
      })
    },
    // 上传图片
    handleAvatarSuccess (res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        //修改用户信息
    },
    // 图片上传之前的校验方法
    beforeAvatarUpload (file) {
      
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
        this.imageUrl = URL.createObjectURL(file);
        this.file = file

      // 修改
      const formData = new FormData()
      if (this.file.name != 'File') {
        formData.set('id', this.id)
        formData.set('file', this.file, this.file.name)
      }
      this.$axios
        .post('/sysUser/updateUserFile', formData)
        .then((res) => {
          if (res.data.code == '200') {
            this.$message('修改头像成功', 'success')
            // 重新刷新页面
            window.sessionStorage.setItem('token', res.data.data.token)
            window.sessionStorage.setItem('avatarUrl', res.data.data.avatarUrl)
            this.file = File
            this.$router.go(0)
          } else {
            this.$message.error('上传头像失败！')
          }
        })
        .catch((error) => {
          this.$message.error('服务器崩溃了，请稍后再尝试使用！')
        })
      return false
    },
    // 上传图片  鼠标移入
    handleMouseEnter () {
      this.isShowUpload = true
    },
    // 上传图片  鼠标移出
    handleMouseLeave () {
      this.isShowUpload = false
    },
    // 点击tag
    handleClick (tab, event) {
    },
    // 修改个人信息
    upUserInfo () {
      this.$refs.userInfoForm.validate((valid) => {
        if (valid) {
          this.$axios
            .put('/sysUser/updateUser', this.userInfoForm)
            .then((res) => {
              if (res.data.code == '200') {
                this.$message('修改信息成功', 'success')
                this.$router.go(0)
              } else {
                this.$message.error(res.data.data)
              }
            })
            .catch((error) => {
              this.$message.error('服务器崩溃了，请稍后再尝试使用！')
            })
        } else {
          this.$message.error('信息格式有误！')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 修改密码
    updatePassword () {
      this.passForm.id = this.id
      this.$refs.passForm.validate((valid) => {
        if (valid) {
          this.$axios
            .put('/sysUser/updatePassword', this.passForm)
            .then((res) => {
              if (res.data.code == '200') {
                this.$message('修改密码成功', 'success')
                this.$router.go(0)
              } else {
                this.$message.error(res.data.data)
              }
            })
            .catch((error) => {
              this.$message.error('服务器崩溃了，请稍后再尝试使用！')
            })
        } else {
        }
      })
    }
  }
}
</script>

<style  scoped>
.left_card {
}
.header {
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
  font-size: 20px;
  font-weight: 800;
  border-bottom: 1px solid #e7eaec;
}
.img {
  height: 120px;
  padding: 20px 0;
  border-bottom: 1px solid #e7eaec;
  position: relative;
}
.img_center {
  width: 120px;
  height: 120px;
  border-radius: 60px;
  position: absolute;
  top: 20px;
  left: calc(50% - 60px);
}
.img_avg {
  width: 120px;
  position: absolute;
  height: 120px;
  border-radius: 60px;
}
.upload_img {
  position: absolute;
  background: #1d1d1d;
  opacity: 0.5;
  z-index: 1;
  width: 120px;
  height: 120px;
  border-radius: 60px;
}
.user_info {
  padding: 20px 20px;
  width: calc(100% - 40px);
}
.user_info li {
  list-style: none;
  height: 40px;
  width: 100%;
  line-height: 40px;
  border-bottom: 1px solid #e7eaec;
}
.user_info i {
  width: 20px;
  height: 20px;
  margin-right: 10px;
}
.user_info .title {
  font-size: 14px;
  font-weight: 600;
}
.info {
  float: right;
  margin-right: 10px;
  font-size: 14px;
}

/**图片上传**/

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar-uploader-icon::before {
  color: #ffff;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
